package nero.yncc.com.createart.utils;

/**
 * Created by nero on 17-6-27.
 */

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import nero.yncc.com.createart.custom.MyRecyclerView;

/**
 * 自动换行布局管理
 * Created by chengxiakuan on 2016/10/14.
 */
public class MyLayoutManager extends RecyclerView.LayoutManager {
    int width=0;
    public MyLayoutManager(Context context) {
        this.setAutoMeasureEnabled(true);
        WindowManager manager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics=new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(metrics);
        width=metrics.widthPixels;
    }

    @Override
    public MyRecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new MyRecyclerView.LayoutParams(
                MyRecyclerView.LayoutParams.WRAP_CONTENT,
                MyRecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }

    @Override
    public void onLayoutChildren(MyRecyclerView.Recycler recycler, MyRecyclerView.State state) {
        detachAndScrapAttachedViews(recycler);
        int sumWidth =getWidth();

        int curLineWidth = 0, curLineTop = 0;
        int lastLineMaxHeight = 0;
        for (int i = 0; i < getItemCount(); i++) {
            View view = recycler.getViewForPosition(i);

            addView(view);
            measureChildWithMargins(view, 0, 0);
            int width = getDecoratedMeasuredWidth(view);
            int height = getDecoratedMeasuredHeight(view);

            curLineWidth += width;
            if (curLineWidth <= sumWidth) {//不需要换行
                layoutDecorated(view, curLineWidth - width, curLineTop, curLineWidth, curLineTop + height);
                //比较当前行多有item的最大高度
                lastLineMaxHeight = Math.max(lastLineMaxHeight, height);
            } else {//换行
                curLineWidth = width;
                if (lastLineMaxHeight == 0) {
                    lastLineMaxHeight = height;
                }
                //记录当前行top
                curLineTop += lastLineMaxHeight;

                layoutDecorated(view, 0, curLineTop, width, curLineTop + height);
                lastLineMaxHeight = height;
            }
        }

    }

}
